

const NFs = require('fs');
const NPath = require('path');

const Database = new require('../../database/index.js');
const Db = new Database();

// 根目录
const rootPath = NPath.join(__dirname, '../../');

// {
//   status: 200,
//   msg: '获取列表成功 ',
//   data: {
//     a: '111',
//     b: '222'
//   },
//   code: 200
// }

class ChartController {
  // 获取列表
  async list(urlParams) {
    let param = {
      sort: urlParams.get('sort') || 'viewCount',
      type: urlParams.getAll('type[]') || [],
      order: urlParams.get('order') || 'desc',
      pageNo: urlParams.get('pageNo')  || 0,
      pageSize: urlParams.get('pageSize') || 10,
    }

    // 获取索引文件列表
    let filepaths = await Db.indexList();
    // 获取所有索引列表
    let list = [];
    for (let i = 0; i < filepaths.length; i++) {
      list.push(...await Db.indexDetail(filepaths[i], param.sort, param.type));
    }
    // 根据参数排序
    list = list.sort((prev, next) => {
      let res = Number(prev.s) > Number(next.s) ? 1 : -1;
      res = param.order == 'desc' ? res = res * -1 : res;
      return res;
    })
    // 分页
    let pageNo = Number(param.pageNo),
        pageSize = Number(param.pageSize);
    let start = pageNo*pageSize;
    let end = start+pageSize;
    list = list.slice(start, end);
    // 根据id获取对应详情
    var resData = [];
    for (let i = 0; i < list.length; i++) {
      let data = await Db.getCardById(list[i].cid);
      resData.push({
        cid: data.cid,
        title: data.title,
        starCount: data.starCount,
        viewCount: data.viewCount,
        userName: data.userName,
      });
    }
    return {
      status: 200,
      msg: '获取列表成功 ',
      data: resData,
      code: 200
    };
  }

  // 获取例子详情
  async detail (urlParams) {
    let cid = urlParams.get('cid');
    let data = await Db.getCardById(cid);
    return {
      status: 200,
      msg: '获取详情成功 ',
      data: data,
      code: 200
    };
  }

  // 处理图片接口
  image (urlParams) {
    return new Promise((resolve, reject) => {
      let imageFilePath = rootPath + 'database/data/image/' + urlParams.imagename;
      let stream = NFs.createReadStream( imageFilePath );
      let responseData = [];//存储文件流
      if (stream) {//判断状态
        stream.on( 'data', function( chunk ) {
          responseData.push( chunk );
        });
        stream.on( 'end', function() {
          let finalData = Buffer.concat( responseData );
          resolve(finalData);
        });
      }
    })
  }

}

module.exports = ChartController;


